import { constantRoutes } from '@/router'
import Layout from '@/layout'

function getJsonTree(data, parentId) {
  var itemArr = []
  for (var i = 0; i < data.length; i++) {
    var node = data[i]
    if (node.parentId === parentId) {
      if(node.type === 0) {
        itemArr.push({
          path:  node.target,
          name: node.name,
          component: Layout,
          meta: {
            title: node.name,
            icon: node.icon
          },
          redirect: "noRedirect",
          children: getJsonTree(data, node.id)
        })
      } else {
        itemArr.push({
          path:  node.target,
          name: node.name,
          component: loadView(node.target),
          meta: {
            title: node.name,
            icon: node.icon
          },
          children: getJsonTree(data, node.id)
        })
      }
     
    }
  }
  return itemArr
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menuList) {
    return new Promise(resolve => {
      const treeShow = menuList.filter(menu => menu.hasShow === 1)
      const tree = getJsonTree(treeShow, '0')
      tree.push({ path: '*', redirect: '/404', hidden: true })
      console.log(tree)
      commit('SET_ROUTES', tree)
      resolve(tree)
    })
  }
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views${view}/index.vue`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
